<?php

namespace mpend\modules\actor\models;

use common\helpers\ArrayHelper;
use common\helpers\Url;
use common\logics\RewardLogic;
use common\models\actor\ActorAttach;
use Yii;
use \common\base\Model;
use common\models\actor\Actor;
use mpend\models\User;
use yii\db\Exception;

class ActorForm extends Model
{

    /**
     * @var 登录用户ID
     */
    public $user_id;

    /**
     * @var 用户名称（真实姓名）
     */
    public $name;

    /**
     * @var 简历性别
     */
    public $gender;

    /**
     * @var 生日
     */
    public $birthday;

    /**
     * @var 联系方式
     */
    public $contact;

    /**
     * @var 头像
     */
    public $avatar;

    /**
     * @var 当前所在地
     */
    public $location;

    /**
     * @var Actor|null;
     */
    private $_model = null;

    private $_user = null;

    //public $attachs;
    public function rules()
    {
        return [
            [['name', 'avatar'], 'required'],
            [['user_id', 'gender'], 'integer'],
            [['birthday', 'contact', 'location'], 'safe'],
            //[['attachs'], 'safe'],
            [['user_id'], 'validateUser'],
        ];
    }

    public function validateUser($attribute)
    {
        if ($this->hasErrors()) {
            return;
        }
        $uid = $this->$attribute;
        $user = User::find()->active()->andWhere([
            'id' => $uid,
        ])->one();
        if (!$user) {
            return $this->addError($attribute, '用户信息不存在或者当前用户被禁用');
        }
        $this->_user = $user;
        $actor = $user->actor;
        if (!$actor) {
            $actor = new Actor();
            $actor->user_id = $user->id;
        }
        $this->_model = $actor;
    }

    public function getModel()
    {
        return $this->_model;
    }

    public function save()
    {
        if (!$this->validate()) {
            $this->validateError('提交内容验证失败');
        }
        $model = $this->model;
        $model->setAttributes([
            'name' => $this->name,
            'gender' => $this->gender,
            'birthday' => $this->birthday,
            'avatar' => Url::attach($this->avatar),
            'location' => $this->location,
            'contact' => $this->contact,
        ]);
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $user = $this->_user;
            $user->setUniqueNickname($this->name);
            $user->setAvatar($this->avatar);
            if (!$user->save()) {
                throw new Exception($user->getErrorMsg());
            }
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            // 奖励贡献值
            $credit = ArrayHelper::getValue(Yii::$app->params, ['credit', 'share'], 0);
            $model->weight += $credit;
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            RewardLogic::share($model->user_id);
            //$attachs = new ActorAttach();
            //$attachs->actor_id = $model->id;
            //$attachs->user_id = $model->user_id;
            //$attachs->image = 1;
            //foreach ($this->attachs as $image) {
            //    $_attach = clone $attachs;
            //    $_attach->setAttributes([
            //        'path' => $image,
            //    ]);
            //    if (!$_attach->save()) {
            //        throw new Exception($_attach->getErrorMsg());
            //    }
            //}
            $transaction->commit();
        } catch (Exception $e) {
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        return $model;
    }

}